package com.ukao.steward.ui.valetRunners.takeLetter;


import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.adapter.FactortTabFragmentAdapter;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.StoreBean;
import com.ukao.steward.bean.ValetCountBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.PopWindowHelp;
import com.ukao.steward.eventbus.BatchEvent;
import com.ukao.steward.eventbus.ShoppEvent;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.ui.valetRunners.sendLetter.DontTakeFragment;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.widget.CustomPopWindow;
import com.ukao.steward.widget.QMUITabSegment;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;

import static com.ukao.steward.R.id.view_pager;

/**
 * 取件tab
 */
public class TakeLetterTabFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(view_pager)
    ViewPager viewPager;
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.all_store_tv)
    TextView allStoreTv;
    @BindView(R.id.all_store_layout)
    LinearLayout allStoreLayout;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;


    private ArrayList<SupportFragment> mFragmentData;
    private Unbinder unbinder;
    private int enterType;
    private Parcelable mParam2;
    private ValetCountBean mValetCountBean;
    public List<StoreBean> mStoreData;
    private FactortTabFragmentAdapter mFactortTabAdapter;
    private CustomPopWindow mStorePop;

    public static TakeLetterTabFragment newInstance(int param1, Parcelable param2) {
        TakeLetterTabFragment fragment = new TakeLetterTabFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putParcelable(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            enterType = getArguments().getInt(ARG_PARAM1);
            mParam2 = getArguments().getParcelable(ARG_PARAM2);
            if (!CheckUtils.isNull(mParam2)) {
                mValetCountBean = (ValetCountBean) mParam2;
            }


        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_take_letter_tab, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        takeCount();
        setStatusBarTintColor(R.color.colorPrimary);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    protected void initView() {
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        mFragmentData = new ArrayList<>();
        mTabSegment.setDefaultSelectedColor(resources.getColor(R.color.blue));
        mTabSegment.setDefaultNormalColor(getColors(R.color.black));
        switch (enterType) {
            case 1:
                mFragmentData.add(TakeLetterFragment.newInstance(1));
                mFragmentData.add(TakeLetterFragment.newInstance(2));
                mFragmentData.add(TakeLetterFragment.newInstance(3));
                title.setText("取件");
                if (!CheckUtils.isNull(mValetCountBean)) {
                    mTabSegment.addTab(new QMUITabSegment.Tab(getTextmMsgCount("未取", mValetCountBean.getTakeReceiveCnt())));
                    mTabSegment.addTab(new QMUITabSegment.Tab(getTextmMsgCount("未交", mValetCountBean.getTakeReceivedCnt())));
                } else {
                    mTabSegment.addTab(new QMUITabSegment.Tab("未取"));
                    mTabSegment.addTab(new QMUITabSegment.Tab("未交"));
                }
                mTabSegment.addTab(new QMUITabSegment.Tab("已交"));
                break;
            case 2:
                allStoreTv.setVisibility(View.VISIBLE);
                title.setText("送件");
                mFragmentData.add(DontTakeFragment.newInstance(1));
                mFragmentData.add(DontTakeFragment.newInstance(2));
                mFragmentData.add(DontTakeFragment.newInstance(3));
                if (!CheckUtils.isNull(mValetCountBean)) {
                    mTabSegment.addTab(new QMUITabSegment.Tab(getTextmMsgCount("未取", mValetCountBean.getSendReceiveCnt())));
                    mTabSegment.addTab(new QMUITabSegment.Tab(getTextmMsgCount("未送", mValetCountBean.getSendReceivedCnt())));

                } else {
                    mTabSegment.addTab(new QMUITabSegment.Tab("未取"));
                    mTabSegment.addTab(new QMUITabSegment.Tab("未送"));
                }

                mTabSegment.addTab(new QMUITabSegment.Tab("已完成"));
                break;
        }
        mFactortTabAdapter=new FactortTabFragmentAdapter(getChildFragmentManager(), mFragmentData);
        viewPager.setAdapter(mFactortTabAdapter);
        viewPager.setOffscreenPageLimit(2);
        mTabSegment.setupWithViewPager(viewPager, false);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.back, R.id.back_btn,R.id.all_store_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.back_btn:
                finish();
                break;
            case R.id.all_store_layout:

                if (CheckUtils.isEmpty(mStoreData)){
                    storelist();
                }else{
                    showPopStoreList();
                }


                break;

        }
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    /**
     * 接收到推送
     */
    @Subscribe
    public void onEvent(BatchEvent event) {
        switch (event.getMessage()) {
            case Msgcount:/*当接收到推送消息的时候就更新界面*/
                takeCount();
                break;
        }
    }

    /**
     * 首页 取送人员消息
     */
    public void takeCount() {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().takeCount(Constant.createParameter(mHashMap)),
                new ApiCallback<ValetCountBean>() {
                    @Override
                    public void onSuccess(ValetCountBean model) {

                        if (model.getHttpCode() == 200) {
                            ValetCountBean mCountBean = model.getData();
                            updateTabCount(mCountBean);

                        }

                    }

                    @Override
                    public void onFinish() {


                    }
                });
    }


    /**
     * 店铺列表
     */
    public void storelist() {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().storelist(Constant.createParameter(mHashMap)),
                new ApiCallback<StoreBean>() {


                    @Override
                    public void onSuccess(StoreBean model) {

                        if (model.getHttpCode() == 200) {
                            mStoreData=model.getData();
                            if (mStoreData==null)  mStoreData=new ArrayList<>();
                            mStoreData.add(0,new StoreBean("全部门店",""));
                            showPopStoreList();

                        }

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();

                    }
                });
    }

    void showPopStoreList() {

              mStorePop= PopWindowHelp.showPopStoreList(allStoreLayout, _mActivity, mStoreData, position -> {
                StoreBean mItem = mStoreData.get(position);
                if (mItem!=null){
                    if (mItem.isCheck())return;
                    mStorePop.dissmiss();
                    mItem.setCheck(true);
                    for (int i = 0; i < mStoreData.size(); i++) {
                        StoreBean storeBean = mStoreData.get(i);
                        if (mStoreData.indexOf(mItem) !=i) {
                            storeBean.setCheck(false);
                        }
                    }

                    allStoreTv.setText(CheckUtils.isEmptyString(mItem.getName()));
                    int  pos=viewPager.getCurrentItem();
                    DontTakeFragment mFragment = (DontTakeFragment) mFactortTabAdapter.getItem(pos);
                    if (mFragment!=null){
                        mFragment.setStoreId(mItem.getId());
                        ShoppEvent.postHasData(ShoppEvent.Message.STORE,mItem.getId());
                    }

                }
            }

            );

    }


    public void updateTabCount(ValetCountBean mCountBean) {
        switch (enterType) {
            case 1: /*取件*/
                mTabSegment.updateTabText(0, getTextmMsgCount("未取", mCountBean.getTakeReceiveCnt()));
                mTabSegment.updateTabText(1, getTextmMsgCount("未交", mCountBean.getTakeReceivedCnt()));
                break;
            case 2: /*送件*/
                mTabSegment.updateTabText(0, getTextmMsgCount("未取", mCountBean.getSendReceiveCnt()));
                mTabSegment.updateTabText(1, getTextmMsgCount("未送", mCountBean.getSendReceivedCnt()));

                break;

        }
        mTabSegment.notifyDataChanged();
    }



    /**
     * 更新送件未取
     *
     * @param msgCount
     */
    public void updataSendNotTake(int msgCount) {
        mTabSegment.updateTabText(0, getTextmMsgCount("未取", msgCount));
        mTabSegment.notifyDataChanged();
    }


    /**
     * 更新送件未送
     *
     * @param msgCount
     */
    public void updataSendNotSend(int msgCount) {
        mTabSegment.updateTabText(1, getTextmMsgCount("未送", msgCount));
        mTabSegment.notifyDataChanged();
    }


    /**
     * 更新取件未取
     *
     * @param msgCount
     */
    public void updataTakeNotTake(int msgCount) {
        mTabSegment.updateTabText(0, getTextmMsgCount("未取", msgCount));
        mTabSegment.notifyDataChanged();
    }


    /**
     * 更新取件未交
     *
     * @param msgCount
     */
    public void updataTakeNotDeal(int msgCount) {
        mTabSegment.updateTabText(1, getTextmMsgCount("未交", msgCount));
        mTabSegment.notifyDataChanged();
    }
    @NonNull
    private String getTextmMsgCount(String title, int count) {
        if (count == 0) {
            return title;
        }
        return title + "(" + count + ")";
    }

}
